package com.croofr.test.zookeeper;

import java.io.File;
import java.io.IOException;

import static com.croofr.global.constants.ZooKeeperConstants.ZOOKEEPER_HOME_IDENTIFIER;
import static com.croofr.global.constants.ZooKeeperConstants.ZOOKEEPER_RUN_SCRIPT;


/**
 * Start and stop ZooKeeper server in test.
 * Path to ZooKeeper server home directory is specifed by "ZK_HOME" system property.
 * <p/>
 * User: bednar<br/>
 * Date: Jan 31, 2010<br/>
 * Time: 9:58:22 AM
 */
public class ZooKeeperMain
{
    private String zooKeeperScriptPath;

    {
        initializeZooKeeperScript();
    }

    private void initializeZooKeeperScript()
    {
        String zooKeeperHome = System.getenv(ZOOKEEPER_HOME_IDENTIFIER);

        StringBuffer script = new StringBuffer();

        script.append(zooKeeperHome);
        script.append(File.separator);
        script.append("bin");
        script.append(File.separator);
        script.append(ZOOKEEPER_RUN_SCRIPT);

        zooKeeperScriptPath = script.toString();
    }

    /**
     * Start ZooKeeper server
     *
     * @throws IOException during invocation start on zkServer.sh
     */
    public void startZooKeeper() throws IOException
    {
        Runtime.getRuntime().exec(new String[]{zooKeeperScriptPath, "start"});
    }

    /**
     * Stop ZooKeeper server
     *
     * @throws IOException during invocation stop on zkServer.sh
     */
    public void stopZooKeeper() throws IOException
    {
        Runtime.getRuntime().exec(new String[]{zooKeeperScriptPath, "stop"});
    }
}
